import axios from "axios";
import {BEARER_PREFIX, TOKEN_NAME} from "@/util/constants.js";
import {confirm} from "@/util/message.js";
import {ElMessage} from "element-plus";

// 配置请求的根路径
axios.defaults.baseURL = 'http://localhost:8081';
// 封装get请求
export const doGet = (url, params) => {
    return axios({
        url: url, method: 'get', params: params
    });
}
// 封装post请求
export const doPost = (url, data) => {
    return axios({
        url: url, method: 'post', data: data
    });
}
// 封装put请求
export const doPut = (url, data) => {
    return axios({
        url: url, method: 'put', data: data
    });
}
// 封装delete请求
export const doDelete = (url, data) => {
    return axios({
        url: url,
        method: 'delete',
        data: data
    });
}
// 封装下载请求
export const doDownload = (url, params) => {
    return axios({
        method: 'get',
        url: url,
        params: params,
        responseType: 'blob'
    });
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    //从本地获取token
    let token = localStorage.getItem(TOKEN_NAME);
    //判断token是否有值
    if (token) {
        //将本地的token放到请求头中
        config.headers.Authorization = BEARER_PREFIX + token;
        //用户选中记住我
        config.headers['RememberMe'] = true
    } else {
        //从会话存储中获取token放到请求头中
        token = sessionStorage.getItem(TOKEN_NAME);
        config.headers.Authorization = BEARER_PREFIX + token;
        config.headers['RememberMe'] = false
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 判断响应状态码是否为>900，如果是则删除token并跳转到登录页面
    if (response.data.code > 900) {
        confirm('登录过期，请重新登录').then(() => {
            //删除token
            localStorage.removeItem(TOKEN_NAME);
            //删除会话存储中的token
            sessionStorage.removeItem(TOKEN_NAME);
            window.location.href = '/';
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '请重新登录',
            })
        })

        //跳转到登录页面

    }
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});
